package tools.utils
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import kiwi.util.sprintf;

	public class SaveSmallPackageUtil
	{
		
		private var dir : String;
		private var quality:int;
		private var fileName:String;
		
		public function SaveSmallPackageUtil(dirs:String,fileNames:String,qualitys:int)
		{
			this.dir = dirs;
			this.quality = qualitys;
			this.fileName = fileNames;
			
			startPackage();
			
		}
		
		private function startPackage():void{
			var jsfl : String = <![CDATA[
				//pkg(fl.browseForFolderURL("请选择素材文件夹"),80);
				function pkg(folderPath,spriteName,quality){
					fl.trace("开始:"+spriteName);
					// 清理输出
					//fl.outputPanel.clear();
					// 创建新文件
					fl.createDocument();
					var dom = fl.getDocumentDOM();
					var lib = fl.getDocumentDOM().library;
					// 导入类
					FLfile.write(folderPath+"/ENTRY.as","package{import flash.display.*;public class ENTRY extends MovieClip{TEXTURE_CONF;TEXTURE;}}");
					dom.docClass="ENTRY";
					fl.trace("主脚本生成成功");
					FLfile.write(folderPath+"/TEXTURE_CONF.as","package{import flash.utils.*;[Embed(source=\""+spriteName+".xml\",mimeType=\"application/octet-stream\")]public class TEXTURE_CONF extends ByteArray {}}");
					fl.trace("导出配置文件成功");
					// 打开文件夹
					dom.importFile(folderPath + "/"+spriteName+".png");
					fl.trace("导入图片成功");
					lib.selectItem(spriteName+".png");
					// 清场
					dom.selectAll(); 
					dom.deleteSelection();
					// 导出位图链接
					lib.setItemProperty("allowSmoothing",false);
					lib.setItemProperty("linkageExportForAS",true);
					lib.setItemProperty("linkageExportInFirstFrame",true);
					lib.setItemProperty("linkageBaseClass","flash.display.BitmapData");
					lib.setItemProperty("linkageClassName","TEXTURE");
					lib.setItemProperty("compressionType","photo");
					lib.setItemProperty("quality",quality);
					fl.trace("导出图片成功");
					
					// 保存配置类
					fl.saveDocument(dom,folderPath+"/"+spriteName+".fla");
					dom.swfJPEGQuality=quality;
					dom.exportSWF(folderPath+"/"+spriteName+".swf",true);
					dom.close();
					FLfile.remove(folderPath+"/ENTRY.as");
					FLfile.remove(folderPath+"/TEXTURE_CONF.as");
					FLfile.remove(folderPath+"/"+spriteName+".fla");
					FLfile.remove(folderPath+"/"+spriteName+".jsfl");
					fl.trace("---------------------------------");
				}
			]]>;
			var workdir : File = File.applicationDirectory.resolvePath(dir);
			var out : FileStream = new FileStream();
			var jsflFile : File = workdir.resolvePath(fileName+".jsfl");
			out.open(jsflFile, FileMode.WRITE);
			out.writeByte(0xEF);
			out.writeByte(0xBB);
			out.writeByte(0xBF);
			out.writeUTFBytes(jsfl);
			out.writeUTFBytes(sprintf("pkg(\"file:///%s\",\"%s\",%d);", dir.replace(/\\/g, "/") , fileName, quality));
			out.close();
		}
	}
}